package com.cloudpivot.receivales.ding.basic.service.impl;

import com.cloudpivot.receivales.contract.configuration.CrmConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.swing.text.html.parser.Entity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * crm 请求api服务
 */

@Component
@Slf4j
public class HttpAPIServiceForDing {

    @Autowired
    private CrmConfig crmConfig;

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${myprops.ding-private}")
    private String DINGMSGAPI;

    /**
     * crm专用 需求:需要增加请求头的get请求
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetCrm(String url, String header) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);
        httpGet.setHeader("MSCRMCallerID", header);

        this.httpClient = this.crmConfig.getAuthHttp();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * crm专用
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetCrm(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

        this.httpClient = this.crmConfig.getAuthHttp();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    public String doPostCrm(String url, String str, String header) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);


        if (StringUtils.isBlank(header)) {
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        } else {
            httpPost.setHeader("Content-Type", header);
        }
        httpPost.setHeader("Prefer", "return=representation");

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
//            stringEntity.setContentType("application/json;charset=utf-8");
            httpPost.setEntity(stringEntity);

            // 发起请求
            this.httpClient = this.crmConfig.getAuthHttp();
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        return null;
    }

    /**
     * crm删除记录
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doDelCrm(String url) throws Exception {
        // 声明httpPost请求
        HttpDelete httpDelete = new HttpDelete(url);
        // 加入配置信息
        httpDelete.setConfig(config);
        httpDelete.setHeader("Content-Type", "application/json;charset=utf-8");
        httpDelete.setHeader("Prefer", "return=representation");

        // 发起请求
        this.httpClient = this.crmConfig.getAuthHttp();
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            return "1";
        }

        return null;
    }


    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

//        this.httpClient = this.crmConfig.getAuthHttp();
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {

            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }



    public byte[] doGetToBytes(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

//        this.httpClient = this.crmConfig.getAuthHttp();
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toByteArray(response.getEntity());
        }
        return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetDingParam(String url, Map<String, Object> map,String token) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGetDing(uriBuilder.build().toString(),token);

    }

    public String doGetDing(String url,String token) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);
        httpGet.setHeader("x-acs-dingtalk-access-token", token);
        httpGet.setHeader("Content-Type", "application/json;charset=utf-8");

//        this.httpClient = this.crmConfig.getAuthHttp();
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        String ret=EntityUtils.toString(response.getEntity(), "UTF-8");
        // 判断状态码是否为200
        return ret;
    }

    /**
     * 钉钉用 post请求
     *
     * @param url
     * @param str
     * @param token
     * @return
     * @throws Exception
     */
    public String doPostDing(String url, String str, String token) throws Exception {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("x-acs-dingtalk-access-token", token);

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            String ret= EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("ret:"+ret);
            if (response.getStatusLine().getStatusCode() == 200) {
                return ret;
            }
        }
        return null;
    }

    /**
     * 钉钉用 put请求
     *
     * @param url
     * @param str
     * @param token
     * @return
     * @throws Exception
     */
    public String doPutDing(String url, String str, String token) throws Exception {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);
        // 加入配置信息
        httpPut.setConfig(config);
        httpPut.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPut.setHeader("x-acs-dingtalk-access-token", token);

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPut.setEntity(stringEntity);

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPut);
            int code = response.getStatusLine().getStatusCode();
            String ret = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("返回code：" + code + "  返回msg：" + ret);
            if (code == 200) {
                return ret;
            }
        }
        return null;
    }

    /**
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPost(String url, String str, String header) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        if (StringUtils.isBlank(header)) {
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        } else {
            httpPost.setHeader("Content-Type", header);

        }

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
        }

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        return null;
    }

    /**
     * 不带参数的post 请求
     *
     * @param url
     * @throws Exception
     */
    public String doPost(String url) throws Exception {
        return this.doPost(url, null, null);
    }


}
